#!/bin/bash

# Breeze Admin 部署脚本
# 作者: System Admin
# 日期: $(date +%Y-%m-%d)

set -e

# 配置变量
DEPLOY_DIR="/Users/shouzhi/techzhi/project/gitee/jar-deploy"
JAR_NAME="breeze-admin.jar"
JAR_FILE="$DEPLOY_DIR/$JAR_NAME"
SERVICE_NAME="breeze-admin"
BACKUP_DIR="$DEPLOY_DIR/backup"

echo "开始部署JAVA服务..."

# 创建备份目录
mkdir -p "$BACKUP_DIR"

# 检查当前目录是否包含必要文件
if [ ! -f "$JAR_NAME" ]; then
    echo "错误: 当前目录未找到 $JAR_NAME 文件"
    exit 1
fi

# 停止现有服务（如果运行中）
PID_FILE="$DEPLOY_DIR/${SERVICE_NAME}.pid"
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p "$PID" > /dev/null 2>&1; then
        echo "停止现有服务..."
        "$DEPLOY_DIR/scripts/stop.sh" || true
    fi
fi

# 备份现有jar包
if [ -f "$JAR_FILE" ]; then
    echo "备份现有jar包..."
    BACKUP_NAME=$(basename "$JAR_NAME" .jar)
    cp "$JAR_FILE" "$BACKUP_DIR/${BACKUP_NAME}-$(date +%Y%m%d_%H%M%S).jar"
fi

# 复制新的jar包
echo "复制新的jar包..."
cp "$JAR_NAME" "$JAR_FILE"
chmod +x "$JAR_FILE"

# 确保脚本文件有执行权限
chmod +x scripts/*.sh

echo "部署完成!"
echo ""
echo "使用方法:"
echo "  启动服务: ./scripts/start.sh"
echo "  停止服务: ./scripts/stop.sh"
echo "  健康检查: ./scripts/health-check.sh"
echo "  快速启动: ./quick-start.sh (开发模式)"
echo ""
echo "服务访问地址:"
echo "  应用访问: http://localhost:34080/breeze/api"
echo "  健康检查: http://localhost:34080/actuator/health"
echo ""
echo "日志文件位置:"
echo "  应用日志: $DEPLOY_DIR/logs/${SERVICE_NAME}.log"
echo "  错误日志: $DEPLOY_DIR/logs/error.log"
echo "  启动日志: $DEPLOY_DIR/logs/startup.log"
echo ""
echo "配置文件位置:"
echo "  应用配置: $DEPLOY_DIR/config/application.yml"
echo "  生产配置: $DEPLOY_DIR/config/application-prod.yml"
echo "  日志配置: $DEPLOY_DIR/config/logback-spring.xml"
echo "  JVM参数: $DEPLOY_DIR/config/java-opts.conf"
echo ""
echo "systemd服务配置: $DEPLOY_DIR/systemd/${SERVICE_NAME}.service"
echo ""
echo "要安装为系统服务，请运行:"
echo "  sudo cp systemd/${SERVICE_NAME}.service /etc/systemd/system/"
echo "  sudo systemctl daemon-reload"
echo "  sudo systemctl enable ${SERVICE_NAME}"
